package com.gitee.lw114514.webapp_memorandium.dao.Impl;

import cn.hutool.core.io.IoUtil;
import com.gitee.lw114514.webapp_memorandium.dao.TaskDao;
import org.springframework.stereotype.Repository;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Repository
public class TaskDaoImpl implements TaskDao {
    @Override
    public List<String> FindUncompleteTask() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("uncomplete.csv");
        // 添加空值检查
        if (inputStream == null) {
            System.err.println("uncomplete.csv文件未找到");
            return new ArrayList<>();
        }
        ArrayList<String> lines = IoUtil.readLines(inputStream, StandardCharsets.UTF_8, new ArrayList<>());
        return lines;
    }

    @Override
    public List<String> FindCompleteTask() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("complete.csv");
        // 添加空值检查
        if (inputStream == null) {
            System.err.println("complete.csv文件未找到");
            return new ArrayList<>();
        }
        ArrayList<String> lines = IoUtil.readLines(inputStream, StandardCharsets.UTF_8, new ArrayList<>());
        return lines;
    }

    /// //////////////////////////////////////////////////////////////////////////////////////

    @Override
    public boolean deleteTaskById(Integer taskId, Boolean taskStatus) {
        // 从两个文件中查找并删除任务
        if (taskStatus) {
            //若任务状态为true已完成，则从已完成文件中删除
            return deleteTaskFromFile("complete.csv", taskId);
        } else {
            //若任务状态为false未完成，则从未完成文件中删除
            return deleteTaskFromFile("uncomplete.csv", taskId);
        }
    }


    private boolean deleteTaskFromFile(String fileName, Integer taskId) {
        try {
            // 获取文件输入流
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
            if (inputStream == null) {
                System.err.println(fileName + "文件未找到");
                return false;
            }

            // 读取所有行
            ArrayList<String> lines = IoUtil.readLines(inputStream, StandardCharsets.UTF_8, new ArrayList<>());
            IoUtil.close(inputStream);

            // 查找并移除匹配的任务行
            boolean found = false;
            List<String> newLines = new ArrayList<>();

            for (String line : lines) {
                if (!line.trim().isEmpty()) {
                    String[] parts = line.split(",");
                    if (parts.length > 0 && Integer.parseInt(parts[0]) == taskId) {
                        found = true;
                        // 不添加这一行，相当于删除
                        System.out.println("已删除任务：" + line);
                    } else {
                        newLines.add(line);
                        // 添加这一行
                    }
                }
            }

            // 如果找到了任务，则重写文件
            if (found) {
                // 获取文件的绝对路径
                String filePath = this.getClass().getClassLoader().getResource(fileName).getPath();
                // 处理Windows路径前缀
                if (filePath.startsWith("/")) {
                    filePath = filePath.substring(1);
                }

                // 写入更新后的内容
                try (FileWriter writer = new FileWriter(filePath, StandardCharsets.UTF_8)) {
                    for (String line : newLines) {
                        writer.write(line + "\n");
                    }
                }

                return true;
            }

            return found;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /// ////////////////////////////////////////////////////////////////////////////////

    //添加任务的dao
    @Override
    public boolean addTask(String taskDescription, String taskDate) {
        System.out.println("(dao)添加任务：" + taskDescription + " " + taskDate);
        //1.获取未完成任务的csv文件输入流
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("uncomplete.csv");
            // 获取文件的绝对路径
            String filePath = this.getClass().getClassLoader().getResource("uncomplete.csv").getPath();
            if (inputStream == null) {
                System.err.println("uncomplete.csv文件未找到");
                return false;
            }
            ArrayList<String> lines = IoUtil.readLines(inputStream, StandardCharsets.UTF_8, new ArrayList<>());
            IoUtil.close(inputStream);

            String last_line = lines.get(lines.size() - 1);
            int last_id = Integer.parseInt(last_line.split(",")[0]);//获取最后一行的id

            //2.将传入的新任务添加到文件末尾
            int new_id = last_id + 1;
            String new_line = new_id + "," + taskDescription + "," + taskDate + "," + "false";
            System.out.println("已添加任务：" + new_line);
            lines.add(new_line);
            //3.将文件内容覆盖写入文件
            try (FileWriter writer = new FileWriter(filePath, StandardCharsets.UTF_8)) {
                for (String line : lines) {
                    writer.write(line + "\n");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////

    @Override
    public boolean completeTaskById(Integer taskId) {
        boolean complete_flag = false;
        boolean uncomplete_flag = false;
        System.out.println("任务完成：" + taskId);

        //1.获取未完成任务和已完成任务的csv文件输入流
        try {
            InputStream uncompleteInputStream = this.getClass().getClassLoader().getResourceAsStream("uncomplete.csv");
            InputStream completeInputStream = this.getClass().getClassLoader().getResourceAsStream("complete.csv");
            //获取已完成任务的csv的绝对路径
            String completeFilePath = this.getClass().getClassLoader().getResource("complete.csv").getPath();
            //获取未完成任务的csv的绝对路径
            String uncompleteFilePath = this.getClass().getClassLoader().getResource("uncomplete.csv").getPath();
            if (uncompleteInputStream == null || completeInputStream == null) {
                System.err.println("uncomplete.csv或complete.csv文件未找到");
                return false;
            }
            ArrayList<String> uncompleteLines = IoUtil.readLines(uncompleteInputStream, StandardCharsets.UTF_8, new ArrayList<>());
            ArrayList<String> completeLines = IoUtil.readLines(completeInputStream, StandardCharsets.UTF_8, new ArrayList<>());
            IoUtil.close(uncompleteInputStream);
            IoUtil.close(completeInputStream);
            for (String line : uncompleteLines) {
                String[] parts = line.split(",");
                // 判断是否是目标任务
                if (parts.length > 0 && Integer.parseInt(parts[0]) == taskId) {
                    // 将目标任务添加到已完成任务列表
                    int last_id = completeLines.size() > 0 ? Integer.parseInt(completeLines.get(completeLines.size() - 1).split(",")[0]) : 0;
                    int new_id = last_id + 1;
                    String new_line = new_id + "," + parts[1] + "," + parts[2] + "," + "true";
                    boolean add = completeLines.add(new_line);
                    System.out.println("已添加已完成任务到列表：" + new_line);
                    if (!add) {
                        System.err.println("添加已完成任务失败");
                        return false;
                    }
                    //将新的已完成任务写入文件
                    try (FileWriter writer = new FileWriter(completeFilePath, StandardCharsets.UTF_8)) {
                        for (String completeLine : completeLines) {
                            writer.write(completeLine + "\n");
                        }
                        System.out.println("已写入已完成任务文件：" + completeFilePath);
                        complete_flag = true;
                    } catch (IOException e) {
                        System.out.println("写入已完成任务文件失败");
                        throw new RuntimeException(e);
                    }
                    System.out.println("已添加已完成任务：" + new_line);


                    // 删除目标任务
                    uncompleteLines.remove(line);
                    System.out.println("已删除目标任务中目标：" + line);
                    try (FileWriter writer = new FileWriter(uncompleteFilePath, StandardCharsets.UTF_8)) {
                        for (String uncompleteLine : uncompleteLines) {
                            writer.write(uncompleteLine + "\n");
                            System.out.println("已写入未完成任务文件：" + uncompleteFilePath);
                            uncomplete_flag = true;
                        }
                    } catch (IOException e) {
                        System.out.println("写入未完成任务文件失败");
                        throw new RuntimeException(e);
                    }
                    System.out.println("已删除目标任务：" + line);
                }
            }
        } catch (RuntimeException e) {
            System.out.println("任务完成失败");
            throw new RuntimeException(e);
        }
        return complete_flag && uncomplete_flag;
    }
}






